package woc.dao.base;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;


public abstract class RootDAOImpl<T> extends HibernateDaoSupport implements RootDAO<T> {

	protected Logger logger = Logger.getLogger(getClass());
	private Class<T> clazz;

	public RootDAOImpl(Class<T> clazz) {
		this.clazz = clazz;
	}
	
	@Override
	public void delete(T entity) {
		//Mark entity as deleted
		try{
			Method setDeletedMethod = clazz.getDeclaredMethod("setDeleted", Boolean.class);
			setDeletedMethod.invoke(entity, true);
			getHibernateTemplate().saveOrUpdate(entity);		
		}catch(Exception e){
			e.printStackTrace();
		}
		//actually delete
//		getHibernateTemplate().delete(entity);
	}
	@Override
	public void deleteAll(Collection<T> entities) {
		getHibernateTemplate().deleteAll(entities);
	}
	@Override
	public void saveOrUpdateAll(Collection<T> entities) {
		getHibernateTemplate().saveOrUpdateAll(entities);
	}
	@SuppressWarnings("unchecked")
	@Override
	public T get(Serializable id) {
		return (T)getHibernateTemplate().get(clazz, id);
	}
	@SuppressWarnings("unchecked")
	@Override
	public T load(Serializable id) {
		return (T)getHibernateTemplate().load(clazz, id);
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<T> find(String hql){
		return (List<T>)getHibernateTemplate().find(hql);
	}		
	@Override
	public Object execute(HibernateCallback action) {
		return getHibernateTemplate().execute(action);
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<T> findByNamedParam(String queryString, String paramName,Object value) {
		return getHibernateTemplate().findByNamedParam(queryString, paramName, value);
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<T> findByNamedParam(String queryString, String[] paramNames,Object[] values) {
		return getHibernateTemplate().findByNamedParam(queryString, paramNames, values);
	}		
	@SuppressWarnings("unchecked")
	@Override
	public List<T> getByExampleList(T entity) {
		return getHibernateTemplate().findByExample(entity);
	}
	@Override
	public T getByExampleUnique(T entity) {
		return null;
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<T> listAll() {
		return getHibernateTemplate().loadAll(clazz);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> loadAll() {
		return getHibernateTemplate().loadAll(clazz);
	}
	@SuppressWarnings("unchecked")
	@Override
	public T save(T entity) {
		return (T)getHibernateTemplate().save(entity);		
	}
	@Override
	public void saveOrUpdate(T entity) {
		getHibernateTemplate().saveOrUpdate(entity);
	}
	@Override
	public void update(T entity) {
		getHibernateTemplate().update(entity);
	}
}
